import Pojo.User;
import com.mysql.cj.jdbc.Driver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Luming
 * @Date 2024/5/15 20:01
 * @Description:
 */
@WebServlet("/SelectServlet")
public class SelectServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        
        String url = "jdbc:mysql://127.0.0.1:3306/WebTest";
        String user = "root";//数据库名
        String passwd = "1473992017";//登录数据库密码
        
        try {
            // 加载JDBC驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //1、注册驱动
            Driver driver = new com.mysql.jdbc.Driver();
            DriverManager.registerDriver(driver);
            //2.获取连接
            Connection connection = DriverManager.getConnection(url, user, passwd);
            //3、获取数据库操作对象
            Statement statement = connection.createStatement();
            //4.sql语句
            String sql = "select * from user_info";
            //5.执行sql语句后的结果
            ResultSet resultSet = statement.executeQuery(sql);
            //6.封装
            List<User> userList = new ArrayList<>();
            while (resultSet.next()) {
                User userTemp = new User();
                userTemp.setId(resultSet.getInt("id"));
                userTemp.setUsername(resultSet.getString("username"));
                userTemp.setPassword(resultSet.getString("password"));
                userTemp.setInformation(resultSet.getString("information"));
                userTemp.setHobby(resultSet.getString("hobby"));
                userList.add(userTemp);
            }
            // 将 userList 存储到 request 中，以便在 JSP 中使用
            request.setAttribute("userList", userList);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        request.getRequestDispatcher("Table.jsp").forward(request,response);
    }
}
